package com.yisu.expressway.utils;

import android.text.TextUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
    private BigDecimal b;

    private StringUtil() {

    }

    public static int parseInt(String str, int ev) {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            return ev;
        }
    }

    public static int parseInt(String str) {
        return parseInt(str, -1);
    }

    public static long parseLong(String str, long ev) {
        try {
            return Long.parseLong(str);
        } catch (NumberFormatException e) {
            return ev;
        }
    }

    public static long parseLong(String str) {
        return parseLong(str, -1L);
    }

    public static double parseDouble(String str, double ev) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return ev;
        }
    }

    public static boolean isNullOrEmpty(String str) {
        if (str == null || str.trim().length() == 0) {
            return true;
        } else {
            return false;
        }
    }

    public static String trim(String str) {
        try {
            return str.trim();
        } catch (Exception e) {
            return "";
        }
    }

    public static String InsertEscChar(String str, char escapeChar) {
        if (escapeChar == '%') {
            if (str.indexOf(String.valueOf('%')) != -1) {
                str = str.replaceAll("%", "\n%");
            }
        } else if (escapeChar == '_') {
            if (str.indexOf(String.valueOf('_')) != -1) {
                str = str.replaceAll("_", "\n_");
            }
        } else if (escapeChar == '\'') {
            if (str.indexOf(String.valueOf('\'')) != -1) {
                str = str.replaceAll("\'", "\''");
            }
        }
        return str;
    }

    public static String unitConversion(String priceInfo) {
        try {
            double price = 0.0;
            if (priceInfo == null || "0".equalsIgnoreCase(priceInfo) || priceInfo.trim().length() == 0) {
                return "0.00";
            }
            if (priceInfo != null && priceInfo.trim().length() != 0) {
                price = StringUtil.parseDouble(priceInfo, 0.0) / 100.0;
            }

            DecimalFormat format = new DecimalFormat("###.00");

            return format.format(price);
        } catch (Exception e) {
            return priceInfo;
        }
    }

    /*
     * Replace the special characters in XML with entity references.
     * Note: replaceAll("&", "&amp;") should be foremost among all the methods "replaceAll".
     */
    public static String replaceCharWithEntity(String data) {

        data = data.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("'", "&apos;").replaceAll("\"", "&quot;");
        return data;
    }

    /*
     * Revert the entity references to actual characters.
     * Note: replaceAll("&amp;", "&") should be put at the end of entity references restoration.
     */
    public static String restoreEntityToChar(String data) {

        data = data.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&apos;", "'").replaceAll("&quot;", "\"").replaceAll("&nbsp;", " ")
                .replaceAll("&amp;", "&");

        return data;
    }

    public static String replaceAllCharWithEntity(String data) {
        data = data.replaceAll("<(.*?)>", "");
        return data;
    }

    public static String convertEscapeSequence(String orig) {
        if (orig == null)
            return null;
        orig = orig.replaceAll("&ldquo;", "\u201c");
        orig = orig.replaceAll("&rdquo;", "\u201d");
        orig = orig.replaceAll("&hellip;", "\u2026");
        orig = orig.replaceAll("&mdash;", "\u2014");
        orig = orig.replaceAll("&lsquo;", "\u2018");
        orig = orig.replaceAll("&rsquo;", "\u2019");
        orig = orig.replaceAll("&middot;", "\u00b7");
        return orig;
    }

    /**
     * if a url's suffix equals ".jpg" or ".png", we judge it is a image resource url.
     *
     * @param url
     * @return
     */
    public static boolean isImageResource(String url) {
        String suffix = "";
        try {
            suffix = url.substring(url.length() - 4);
        } catch (IndexOutOfBoundsException e) {

        }

        if (".jpg".equalsIgnoreCase(suffix) || ".png".equalsIgnoreCase(suffix)) {
            return true;
        }
        return false;
    }

    /*get number from string
     * */
    public static String getNumFromStr(String str) {
        String regex = "\\d*";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        while (m.find()) {
            if (!"".equals(m.group()))
                return m.group();
        }
        return "";
    }

    /**
     * check String is number and is integer type
     *
     * @param str
     * @return result
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    //recently read calc pasted time
    private static SimpleDateFormat SDF_ = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    public static String getRectentlyTime(long readTime) {
        String result = "";
        long currentTime = System.currentTimeMillis();
        Calendar currentCal = Calendar.getInstance();
        Calendar recentCal = Calendar.getInstance();
        recentCal.setTimeInMillis(readTime);
        int duringDay = currentCal.get(Calendar.DAY_OF_MONTH) - recentCal.get(Calendar.DAY_OF_MONTH);
        int duringMonth = currentCal.get(Calendar.MONTH) - recentCal.get(Calendar.MONTH);
        int duringYear = currentCal.get(Calendar.YEAR) - recentCal.get(Calendar.YEAR);

        if (readTime - currentTime > 0) {
            return "";
        }

        //bug 44584
        if (readTime == 0) {
            return "";
        }

        if (duringYear > 0) {
            SDF_.applyPattern("yyyy-MM-dd");
        } else if (duringMonth > 0 || duringDay > 0) {
            SDF_.applyPattern("MM-dd HH:mm");
        } else {
            SDF_.applyPattern("今天 HH:mm");
        }
        result = SDF_.format(readTime);
        return result;
    }

    /*
        public static String getRectentlyTime(long readTime){
            long currentTime = System.currentTimeMillis() ;
            long during = (currentTime - readTime) /1000;
            String result = "" ;
            Calendar currentCal = Calendar.getInstance();
            Calendar recentCal = Calendar.getInstance() ;
            recentCal.setTimeInMillis(readTime) ;
            int duringDay = currentCal.get(Calendar.DAY_OF_MONTH) - recentCal.get(Calendar.DAY_OF_MONTH);
            int duringMonth = currentCal.get(Calendar.MONTH)  - recentCal.get(Calendar.MONTH);
            int duringYear = currentCal.get(Calendar.YEAR)  - recentCal.get(Calendar.YEAR);

            if(duringYear>0){
                result = duringYear + "年前";
            }else if( duringMonth > 0 ) {
                result = duringMonth + "个月前";
            }else if (duringDay > 0 ) {
                result = duringDay + "天前";
            } else {
                if (during<=60){
                    result = "刚刚" ;
                } else if (during>60 && during<60*60){//一小时下
                    result = during/60 + "分钟前" ;
                } else if(during>=60*60 && during<=60*60*24) {//一小时以上 不跨天
                    result = during/(60*60)  + "小时前";
                }
            }
            return result ;
        }
    */
    public static String getCurrentDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }


    public static String setTextWithoutNull(String text) {
        if (null == text || "null".equals(text)) {
            return "";
        }
        return text;
    }

    /**
     * 手机号验证
     *
     * @param mobile
     * @return 验证通过返回true
     */
    public static boolean isMobile(String mobile) {

        if (TextUtils.isEmpty(mobile)) {
            return false;
        }

        Pattern pattern = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
        Matcher matcher = pattern.matcher(mobile);

        return matcher.matches();
    }


    /**
     * 验证11位纯数字，基地要求更广泛的判断手机号的方式
     *
     * @param text
     * @return 验证通过返回true
     */
    public static boolean isMobile2(String text) {

        if (TextUtils.isEmpty(text)) {
            return false;
        }
        Pattern p = Pattern.compile("^[0-9]{11}$");
        Matcher m = p.matcher(text);

        return m.matches();
    }

    //检查身份证号是否合法
    public static boolean checkIDValid(String id){
        if (null == id){
            return false;
        }

        int lenght = id.length();
        if (18 != lenght){
            return false;
        }

        return true;
    }

    //检查身份证号是否合法
    public static boolean checkCardValid(String id){
        if (null == id){
            return false;
        }

        int lenght = id.length();
        if (lenght < 4){
            return false;
        }

        return true;
    }


    public static String getStandardDate(String timeStr) {

        StringBuffer sb = new StringBuffer();

        long t = Long.parseLong(timeStr);
        long time = System.currentTimeMillis() - (t*1000);
        long mill = (long) Math.ceil(time /1000);//秒前

        long minute = (long) Math.ceil(time/60/1000.0f);// 分钟前

        long hour = (long) Math.ceil(time/60/60/1000.0f);// 小时

        long day = (long) Math.ceil(time/24/60/60/1000.0f);// 天前

        if (day - 1 > 0) {
            sb.append(day + "天");
        } else if (hour - 1 > 0) {
            if (hour >= 24) {
                sb.append("1天");
            } else {
                sb.append(hour + "小时");
            }
        } else if (minute - 1 > 0) {
            if (minute == 60) {
                sb.append("1小时");
            } else {
                sb.append(minute + "分钟");
            }
        } else if (mill - 1 > 0) {
            if (mill == 60) {
                sb.append("1分钟");
            } else {
                sb.append(mill + "秒");
            }
        } else {
            sb.append("刚刚");
        }
        if (!sb.toString().equals("刚刚")) {
            sb.append("前");
        }
        return sb.toString();
    }
    public static String getChatTime(long time) {
        if (time<10000000000l){
            time =1000*time;
        }





        String strDate = "";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date curDate = new Date(time);//获取当前时间
        strDate = formatter.format(curDate);
        return strDate;
    }

     /**默认8个字**/
    public static String getLimitLenthString(String origin){
        return getLimitLenthString(origin,8);
    }

    /**
     *
     * @param origin 原字串
     * @param limit 限制显示长度
     * @return
     */
    public static String getLimitLenthString(String origin,int limit){
        String result = origin;
        if(!isNullOrEmpty(origin)){
            if(origin.trim().length() > limit){
                result = origin.substring(0,limit - 1) + "...";
            }
        }
        return result;
    }

    /**
     * 获取人气值的标准显示规范
     * @param value 人气值
     * @return
     * 不超过100000：显示99999
       大于超过10万：显示10万
       保留1位小数点，四舍五入：如果100200，显示10万；如果103890，显示10.4万
     */
    public static String formatRankValue(int value){
        String result = String.valueOf(value);
        if(value > 100000){
            BigDecimal bg = new BigDecimal(value / 10000.0)
                    .setScale(1, RoundingMode.HALF_UP);
            result = bg.doubleValue() + "万";
        }
        return result;
    }

    /**
     * Convert time to a string
     * @param millis e.g.time/length from file
     * @return formated string (hh:)mm:ss
     */
    public static String millisToString(long millis)
    {
        return StringUtil.millisToString(millis, false);
    }

    /**
     * Convert time to a string
     * @param millis e.g.time/length from file
     * @return formated string "[hh]h[mm]min" / "[mm]min[s]s"
     */
    public static String millisToText(long millis)
    {
        return StringUtil.millisToString(millis, true);
    }

    static String millisToString(long millis, boolean text) {
        boolean negative = millis < 0;
        millis = Math.abs(millis);

        millis /= 1000;
        int sec = (int) (millis % 60);
        millis /= 60;
        int min = (int) (millis % 60);
        millis /= 60;
        int hours = (int) millis;

        String time;
        DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
        format.applyPattern("00");
        if (text) {
            if (millis > 0)
                time = (negative ? "-" : "") + hours + "h" + format.format(min) + "min";
            else if (min > 0)
                time = (negative ? "-" : "") + min + "min";
            else
                time = (negative ? "-" : "") + sec + "s";
        }
        else {
            if (millis > 0)
                time = (negative ? "-" : "") + hours + ":" + format.format(min) + ":" + format.format(sec);
            else
                time = (negative ? "-" : "") + min + ":" + format.format(sec);
        }
        return time;
    }


    /**
     * 简单判断一个URL是否为一个网址,暂时无需用正则
     */

    public static boolean isAvailableWebUrl(String url){
        boolean result = false;
        if(!isNullOrEmpty(url) && (url.startsWith("http") || url.startsWith("www"))){
            result = true;
        }
        return result;
    }
    public static String join(Object[] array, String separator) {
        if (array == null) {
            return null;
        }
        int arraySize = array.length;
        int bufSize = (arraySize == 0 ? 0 : ((array[0] == null ? 16 : array[0].toString().length()) + 1) * arraySize);
        StringBuffer buf = new StringBuffer(bufSize);

        for (int i = 0; i < arraySize; i++) {
            if (i > 0) {
                buf.append(separator);
            }
            if (array[i] != null) {
                buf.append(array[i]);
            }
        }
        return buf.toString();
    }

    /**
     * 是否超过中文字符数限制
     * @param content 输入字符
     * @param limit 中文字符长度
     * @return
     */
    public static boolean isNowMaxLength(String content,int limit){
        boolean result = false;

        byte[] nameBytes = null;
        StringBuilder contentStringBuilder = new StringBuilder(StringUtil.replaceAllBlank(content));
        try {

            nameBytes = contentStringBuilder.toString().getBytes("UTF-8");

            if(nameBytes.length > limit * 3){
                result = true;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 去掉字串中的空格
     * @param str 目标字串
     * @return
     */
    public static String replaceAllBlank(String str){
        str = str.replaceAll(" ","");
        return str;
    }
}
